package com.tbvtc.agriculturalcreditchainserver2025.config;

import com.tbvtc.agriculturalcreditchainserver2025.Interceptor.TokenInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

@Configuration
@Slf4j
public class WebMvcConfiguration extends WebMvcConfigurationSupport {

    @Autowired
    private TokenInterceptor jwtTokenAdminInterceptor;

    // 注入音频存储路径和访问路径（从配置文件读取）
    @Value("${agri.chat.voice.storage-path}")
    private String voiceStoragePath;
    @Value("${agri.chat.voice.access-path}")
    private String voiceAccessPath;

    /**
     * 注册自定义拦截器（清理冗余排除规则）
     */
    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        log.info("开始注册自定义拦截器...");
        registry.addInterceptor(jwtTokenAdminInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns(
                        // 用户相关
                        "/user/**",
                        "/admin/**/login",
                        "/register",
                        "/login/**",
                        "/preview/**",
                        // 静态资源
                        "/favicon.ico",
                        "/**/favicon.ico",
                        "/static/**",
                        "/css/**",
                        "/js/**",
                        "/images/**",
                        // Swagger 相关
                        "/doc.html",
                        "/swagger-ui.html",
                        "/swagger-ui/**",
                        "/webjars/**",
                        "/v3/api-docs/**",
                        "/swagger-resources/**",
                        // 浏览器辅助请求
                        "/.well-known/**",
                        // 音频文件访问路径（已通过资源映射放行，此处可加可不加，保险起见添加）
                        voiceAccessPath + "**"
                );
    }

    /**
     * 设置静态资源映射（关键修正：先配置音频映射，再配置其他静态资源）
     */
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 1. 音频文件映射（优先级最高，避免被/**覆盖）
        // 匹配前端访问路径：voiceAccessPath + 任意子路径（如 /api/voice/20251108/xxx.wav）
        // 映射到本地存储目录：voiceStoragePath（需配置为本地绝对路径，如 D:/agri/voice/）
        log.info("音频访问路径前缀：{}", voiceAccessPath);
        log.info("音频本地存储路径：{}", voiceStoragePath);
        registry.addResourceHandler(voiceAccessPath + "**")
                .addResourceLocations("file:" + voiceStoragePath); // "file:"前缀表示本地文件系统

        // 2. 其他静态资源映射（顺序靠后，不会覆盖音频映射）
        registry.addResourceHandler("/doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        // 移除 registry.addResourceHandler("/**")：避免覆盖所有路径，导致音频映射失效
    }

    @Override
    protected void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(3600);
    }
}